package com.changgou.order.mq.lister;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.order}")
public class PayMessageListener {
    @Autowired
    private OrderService orderService;
    @RabbitHandler
    public void getMessage(String message) throws Exception {
        //支付结果
        Map<String, String> resultMap = JSON.parseObject(message, Map.class);
        System.out.println("监听到的支付结果: " + resultMap);
        //通信标识
        String return_code = resultMap.get("return_code");
        if (return_code.equals("SUCCESS")) {
            //业务结果result_ code
            String result_code = resultMap.get("result_code");
            //订单号out_ _trade. _no
            String out_trade_no = resultMap.get("out_trade_no");
            //支付成功，修改订单状态
            if (result_code.equals("SUCCESS")) {
                //微信支付交易流水号transaction_id
                orderService.updateStatus(out_trade_no,resultMap.get("time_end"),resultMap.get("transaction_id"));
            } else {
                //通知微信关闭失败，关闭时候已经付钱，把订单改成已支付
                //回滚库存自己写，这里只是删除订单
                orderService.delete(out_trade_no);
            }
        }
    }
}
